/**
    @project {
        "templateId": "org.helgoboss.custom",
        "version": "0.1-SNAPSHOT",
        "dependencies": [
            "org.scala-lang:scala-library:2.9.0-1",
            "org.helgoboss:maven:0.1-SNAPSHOT",
            "org.helgoboss:scala-additions:0.1-SNAPSHOT",
            "org.helgoboss:osgi-additions:0.1-SNAPSHOT",
            "org.helgoboss:commandlet-api:0.1-SNAPSHOT",
            "org.helgoboss:commandlet-convenience:0.1-SNAPSHOT"
        ]
    }
*/

package org.helgoboss.maven_commandlet

import org.helgoboss.commandlet._
import org.helgoboss.scala_additions.Implicits._
import org.helgoboss.maven.Maven
import java.io.File
import org.helgoboss.osgi_additions._


class Activator extends OsgiContext with OsgiServiceWatcher with OsgiProvider {
    whenBundleActive {
        whenServicePresent[Maven] {
            new MavenCommandlet(_).providesService[Commandlet]
        }
    }
}

class MavenCommandlet(maven: Maven) extends Commandlet {
    import org.helgoboss.commandlet_convenience.Implicits._

	val id = "org.helgoboss.maven"
    
	def execute(context: ExecutionContext) = {
        val out = context.writer
        val file = new File(context.arguments(0))
        findDirContainingPom(file) match {
            case Some(baseDir) =>
                val pb = maven.prepareExecution(baseDir = baseDir, arguments = context.arguments.drop(1)) #> context.outputStream
                pb.!
            case None =>
                out.println("Couldn't find pom.xml in any parent directory")
                0
        }
	}
    
    private def findDirContainingPom(file: File): Option[File] = {
        if (file.isDirectory) {
            if (file.list.exists(_ == "pom.xml"))
                Some(file)
            else
                Option(file.getParentFile) match {
                    case Some(p) => findDirContainingPom(p)
                    case None => None
                }
        } else {
            findDirContainingPom(file.getParentFile)
        }
    }
    
    
}